{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Linear Regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet import nd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Perceptron(object):\n",
    "    def __init__(self,activator):#初始化权重\n",
    "        self.activator=activator\n",
    "        self.weights=nd.array([])\n",
    "        self.bias=nd.zeros(1)\n",
    "    def __str__(self):#输出字符串\n",
    "        w=self.weights.asnumpy().tolist()\n",
    "        b=self.bias.asnumpy().tolist()\n",
    "        strw='weights:%s'%w\n",
    "        strb='bisa:%s'%b\n",
    "        return strw+'\\n'+strb\n",
    "    def net(self,x):#计算输出值，预测\n",
    "        result=self.activator(nd.dot(self.weights,x)+self.bias)\n",
    "        return result\n",
    "    def updateWeights(self,x,yhat,y,eta):#更新权重和偏差\n",
    "        deltaw=eta*(y-yhat)*x\n",
    "        self.weights+=deltaw\n",
    "        deltab=eta*(y-yhat)\n",
    "        self.bias+=deltab\n",
    "    def epoch(self,xs,ys,eta):#逐个计算预测值\n",
    "        for x,y in zip(xs,ys):\n",
    "            yhat=self.net(x)\n",
    "            self.updateWeights(x,yhat,y,eta)\n",
    "    def train(self,xs,ys,epochs,eta):#初始化权重，迭代更新权重\n",
    "        inputNum=len(xs[0])\n",
    "        self.weights=nd.zeros(inputNum)\n",
    "        for i in range(epochs):\n",
    "            self.epoch(xs,ys,eta)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def f(x):\n",
    "    return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "true_w=nd.array([2,6.6])\n",
    "true_b=nd.array([1.2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def getDataSet():\n",
    "    xs=nd.random_normal(shape=(1000,2))\n",
    "    ys=nd.dot(xs,true_w)+true_b\n",
    "    ys+=0.01*nd.random_normal(shape=ys.shape)\n",
    "    return xs,ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "lrP=Perceptron(f)\n",
    "xs,ys=getDataSet()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "weights:[1.9994938373565674, 6.600113868713379]\n",
      "bisa:[1.200606107711792]\n"
     ]
    }
   ],
   "source": [
    "lrP.train(xs,ys,10,0.01)\n",
    "print(lrP)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## autograd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from mxnet import nd,autograd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x=nd.array([6])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x.attach_grad()#要对x求导"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with autograd.record():#给出损失函数\n",
    "    y=x**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "y.backward()#回传求导"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\n",
       "[ 12.]\n",
       "<NDArray 1 @cpu(0)>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Linear Regression with autograd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet import nd,autograd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "w=nd.random_normal(shape=(2,1))\n",
    "b=nd.zeros((1))\n",
    "params=[w,b]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "for param in params:#要对w,b求导\n",
    "    param.attach_grad()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def net(x):#求预测值\n",
    "    return nd.dot(x,w)+b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def square_loss(yhat,y):#损失函数\n",
    "    return (y.reshape(yhat.shape)-yhat)**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def SGD(params,eta):\n",
    "    for param in params:\n",
    "        param[:]=param-eta*param.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "epochs=10\n",
    "eta=0.1\n",
    "\n",
    "for e in range(epochs):\n",
    "    for x,y in zip(xs,ys):\n",
    "        with autograd.record():\n",
    "            yhat=net(x)\n",
    "            loss=square_loss(yhat,y)\n",
    "        loss.backward()\n",
    "        SGD(params,eta)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\n",
       " [[ 2.00373459]\n",
       "  [ 6.59830904]]\n",
       " <NDArray 2x1 @cpu(0)>, \n",
       " [ 1.19823503]\n",
       " <NDArray 1 @cpu(0)>]"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "params"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
